package com.basic.modules.ykf.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.basic.common.annotation.StringTrim;
import com.basic.common.exception.RRException;
import com.basic.common.utils.*;
import com.basic.common.validator.ValidatorUtils;
import com.basic.modules.sys.controller.AbstractController;
import com.basic.modules.sys.entity.SysUserEntity;
import com.basic.modules.ykf.entity.*;
import com.basic.modules.ykf.service.*;
import com.basic.modules.ykf.service.impl.YkfCustomerServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 客户管理
 *
 * @author maoheng
 * @email 15738859597@163.com
 * @date 2024-04-06 18:40:44
 */
@Slf4j
@RestController
@RequestMapping("ykf/customerShop")
public class YkfCustomerShopController extends AbstractController {

    @Autowired
    private YkfCustomerShopService ykfCustomerShopService;

    @Autowired
    private YkfShopChangeRecordService changeRecordService;

    @Autowired
    private YkfCustomerShopHistoryService historyService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private YkfCustomerSubAccountService subAccountService;
    @Autowired
    private YkfCustomerServiceImpl ykfCustomerService;

    /**
     * 列表-分页
     */
    @StringTrim
    @PostMapping("/page")
    public R list(@RequestBody ParamsModel<YkfCustomerShopEntity> params) {
        PageUtils page = ykfCustomerShopService.queryPage(params);
        return R.ok(page);
    }

    /**
     * 信息
     */
    @PostMapping("/info")
    public R info(@RequestBody YkfCustomerShopEntity param) {
        if (ObjectUtil.isEmpty(param) || ObjectUtil.isEmpty(param.getShopId())) {
            throw new RRException("参数缺失");
        }
        YkfCustomerShopEntity shopEntity = ykfCustomerShopService.getById(param.getShopId());
        return R.ok(shopEntity);
    }

    /**
     * 添加店铺
     */
    @PostMapping("/addShop")
    public R save(@RequestBody YkfCustomerShopEntity ykfCustomerShop) {
        ValidatorUtils.validateEntity(ykfCustomerShop);
        //校验店铺
        validCustomerShop(ykfCustomerShop);
        ykfCustomerShopService.addShop(ykfCustomerShop);
        return R.ok();
    }

    private void validCustomerShop(YkfCustomerShopEntity ykfCustomerShop) {
        if (ObjectUtil.isEmpty(ykfCustomerShop.getShopId())) {
            ykfCustomerShop.setFirstStartDate(ykfCustomerShop.getStartDate());
        }
        QueryWrapper<YkfCustomerShopEntity> shopQueryWrapper = new QueryWrapper<>();
        shopQueryWrapper.lambda()
                .eq(YkfCustomerShopEntity::getCustomerId, ykfCustomerShop.getCustomerId())
                .eq(YkfCustomerShopEntity::getPlatformNo, ykfCustomerShop.getPlatformNo())
                .eq(YkfCustomerShopEntity::getShopGroup, ykfCustomerShop.getShopGroup())
                .eq(YkfCustomerShopEntity::getShopName, ykfCustomerShop.getShopName());
        if (ObjectUtil.isNotEmpty(ykfCustomerShop.getShopId())) {
            shopQueryWrapper.lambda().ne(YkfCustomerShopEntity::getShopId, ykfCustomerShop.getShopId());
        }
        if (ykfCustomerShopService.count(shopQueryWrapper) > 0) {
            throw new RRException("相同客户、平台、分组、店铺不能重复，请检查");
        }
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    public R update(@RequestBody YkfCustomerShopEntity ykfCustomerShop) {
        ValidatorUtils.validateEntity(ykfCustomerShop);
        //校验店铺
        validCustomerShop(ykfCustomerShop);
        ykfCustomerShopService.updateCustomerShop(ykfCustomerShop);
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public R delete(@RequestBody Long[] customerShopIds) {
        ykfCustomerShopService.removeByIds(Arrays.asList(customerShopIds));
        //删除子账号
        QueryWrapper<YkfCustomerSubAccountEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(YkfCustomerSubAccountEntity::getShopId, customerShopIds);
        subAccountService.remove(queryWrapper);
        return R.ok();
    }

    //到期通知
    @PostMapping("/notice")
    public R notice(@RequestBody YkfCustomerShopEntity shopEntity) throws ClientException {
        if (ObjectUtil.isNotEmpty(shopEntity) && ObjectUtil.isNotEmpty(shopEntity.getShopId())) {
            YkfCustomerShopEntity shop = ykfCustomerShopService.getById(shopEntity.getShopId());
            if (ObjectUtil.isNotEmpty(shop) && StrUtil.isNotBlank(shop.getPhone())) {
                //短信
                Map<String, String> map = new HashMap<>();
                map.put("dpmc", shop.getContacts());
                map.put("dqrqtime", ObjectUtil.isNotEmpty(shop.getEndDate()) ? DateUtil.formatDate(shop.getEndDate()) : "");
                smsService.sendMsg(shop.getPhone(), "SMS_133966673", map);
            } else {
                throw new RRException("店铺手机号不存在，请检查");
            }
        } else {
            throw new RRException("参数缺失");
        }
        return R.ok();
    }

    //停止合作
    @PostMapping("/stopCooperation")
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public R stopCooperation(@RequestBody YkfCustomerShopEntity shopEntity) throws ClientException {
        if (ObjectUtil.isNotEmpty(shopEntity) && ObjectUtil.isNotEmpty(shopEntity.getShopId())) {
            YkfCustomerShopEntity shop = ykfCustomerShopService.getById(shopEntity.getShopId());
            if (shopEntity.getEndDate().compareTo(shop.getStartDate()) < 0) {
                throw new RRException("店铺停止日期不能早于开始日期");
            }
            //查询店铺所有子账号分配记录
            QueryWrapper<YkfCustomerSubAccountEntity> subAccountEntityQueryWrapper = new QueryWrapper<>();
            subAccountEntityQueryWrapper.lambda().eq(YkfCustomerSubAccountEntity::getShopId, shopEntity.getShopId())
                    .orderByDesc(YkfCustomerSubAccountEntity::getStartDate);
            List<YkfCustomerSubAccountEntity> list = subAccountService.list(subAccountEntityQueryWrapper);
            if (ObjectUtil.isNotEmpty(list)) {
                Date startDate = list.get(0).getStartDate();
                if (ObjectUtil.isNotEmpty(startDate) && shopEntity.getEndDate().compareTo(startDate) < 0) {
                    throw new RRException("停止日期需大于最后一条子账号分配记录的开始日期，请检查");
                }
                Map<String, List<YkfCustomerSubAccountEntity>> collect = list.stream().collect(Collectors.groupingBy(YkfCustomerSubAccountEntity::getAccountNo));
                for (String accountNo : collect.keySet()) {
                    List<YkfCustomerSubAccountEntity> accountList = collect.get(accountNo);
                    List<YkfCustomerSubAccountEntity> haveDateList = accountList.stream().filter(o -> ObjectUtil.isNotEmpty(o.getStartDate()) && ObjectUtil.isNotEmpty(o.getEndDate())).collect(Collectors.toList());
                    List<YkfCustomerSubAccountEntity> notHaveDateList = accountList.stream().filter(o -> ObjectUtil.isEmpty(o.getStartDate()) || ObjectUtil.isEmpty(o.getEndDate())).collect(Collectors.toList());
                    SysUserEntity user = CommonUtils.getUser();
                    if (ObjectUtil.isNotEmpty(haveDateList)) {
                        haveDateList.sort(Comparator.comparing(YkfCustomerSubAccountEntity::getStartDate));
                        for (int i = 0; i < haveDateList.size(); i++) {
                            UpdateWrapper<YkfCustomerSubAccountEntity> updateWrapper = new UpdateWrapper<>();
                            updateWrapper.lambda().eq(YkfCustomerSubAccountEntity::getSubAccountId, haveDateList.get(i).getSubAccountId())
                                    .set(YkfCustomerSubAccountEntity::getStatus, 2)
                                    .set(YkfCustomerSubAccountEntity::getStopUserId, user.getUserId())
                                    .set(YkfCustomerSubAccountEntity::getStopUserName, user.getName())
                                    .set(YkfCustomerSubAccountEntity::getEndDate, shopEntity.getEndDate())
                                    .set(YkfCustomerSubAccountEntity::getStopTime, shopEntity.getEndDate());
                            if (i == 0) {
                                updateWrapper.lambda().set(YkfCustomerSubAccountEntity::getEndDate, shopEntity.getEndDate());
                            }
                            subAccountService.update(new YkfCustomerSubAccountEntity(), updateWrapper);
                        }
                    }
                    if (ObjectUtil.isNotEmpty(notHaveDateList)) {
                        for (int i = 0; i < notHaveDateList.size(); i++) {
                            UpdateWrapper<YkfCustomerSubAccountEntity> updateWrapper = new UpdateWrapper<>();
                            updateWrapper.lambda().eq(YkfCustomerSubAccountEntity::getSubAccountId, notHaveDateList.get(i).getSubAccountId())
                                    .set(YkfCustomerSubAccountEntity::getStatus, 2)
                                    .set(YkfCustomerSubAccountEntity::getStopUserId, user.getUserId())
                                    .set(YkfCustomerSubAccountEntity::getStopUserName, user.getName())
                                    .set(YkfCustomerSubAccountEntity::getStopTime, shopEntity.getEndDate());
                            subAccountService.update(new YkfCustomerSubAccountEntity(), updateWrapper);
                        }
                    }
                }
            }

            if (ObjectUtil.isNotEmpty(shop) && StrUtil.isNotBlank(shop.getPhone())) {
                //短信
                Map<String, String> map = new HashMap<>();
                map.put("p0", shop.getContacts());
                map.put("p1", shop.getShopName());
                map.put("p2", ObjectUtil.isNotEmpty(shop.getEndDate()) ? DateUtil.formatDate(shop.getEndDate()) : "");
                smsService.sendMsg(shop.getPhone(), "SMS_163625684", map);
            } else {
                log.info("店铺手机号不存在，请检查");
            }
            //更新合作状态
            UpdateWrapper<YkfCustomerShopEntity> updateWrapper = new UpdateWrapper<>();
            SysUserEntity user = getUser();
            updateWrapper.lambda().eq(YkfCustomerShopEntity::getShopId, shopEntity.getShopId())
                    .set(YkfCustomerShopEntity::getStopReason, shopEntity.getStopReason())
//                    .set(YkfCustomerShopEntity::getRealReason, shopEntity.getRealReason())
//                    .set(YkfCustomerShopEntity::getJudgeReason, shopEntity.getJudgeReason())
                    .set(YkfCustomerShopEntity::getRegisterDate, shopEntity.getRegisterDate())
                    .set(YkfCustomerShopEntity::getCooperateStatus, 0)
                    .set(YkfCustomerShopEntity::getStopCooperateDate, shopEntity.getEndDate())
                    .set(YkfCustomerShopEntity::getStopUser, user.getName())
                    .set(YkfCustomerShopEntity::getStopUserDept, user.getDeptName())
                    .set(YkfCustomerShopEntity::getEndDate, DateUtil.date());
            ykfCustomerShopService.update(updateWrapper);

            //查询是否不存在了启用店铺
            QueryWrapper<YkfCustomerShopEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(YkfCustomerShopEntity::getCustomerId, shop.getCustomerId())
                    .eq(YkfCustomerShopEntity::getCooperateStatus, 1);
            int count = ykfCustomerShopService.count(queryWrapper);
            if (count == 0) {
                //更新客户状态
                UpdateWrapper<YkfCustomerEntity> updateWrapper1 = new UpdateWrapper<>();
                updateWrapper1.lambda().eq(YkfCustomerEntity::getCustomerId, shop.getCustomerId())
                        .set(YkfCustomerEntity::getCooperateStatus, 0)
                        .set(YkfCustomerEntity::getStopCooperateDate, null);
                ykfCustomerService.update(updateWrapper1);
            }
        } else {
            throw new RRException("参数缺失");
        }
        YkfCustomerShopEntity shop = ykfCustomerShopService.getById(shopEntity.getShopId());
        YkfShopChangeRecordEntity record = new YkfShopChangeRecordEntity();
        BeanUtil.copyProperties(shop, record);
        record.setUpdTime(DateUtil.date());
        record.setUpdUserId(getUserId());
        record.setUpdUserName(getUser().getName());
        changeRecordService.save(record);

        YkfCustomerShopEntity shop1 = ykfCustomerShopService.getById(shopEntity.getShopId());
        YkfCustomerShopHistoryEntity history = new YkfCustomerShopHistoryEntity();
        BeanUtil.copyProperties(shop1, history);
        history.setOperator(getUser().getName());
        historyService.save(history);
        return R.ok();
    }


    //更新停止合作原因
    @PostMapping("/updateStopCooperation")
    public R updateStopCooperation(@RequestBody YkfCustomerShopEntity shopEntity) {
        if (ObjectUtil.isNotEmpty(shopEntity) && ObjectUtil.isNotEmpty(shopEntity.getShopId())) {
            //更新合作状态
            UpdateWrapper<YkfCustomerShopEntity> updateWrapper = new UpdateWrapper<>();
            SysUserEntity user = getUser();
            updateWrapper.lambda().eq(YkfCustomerShopEntity::getShopId, shopEntity.getShopId())
                    .set(YkfCustomerShopEntity::getStopReason, shopEntity.getStopReason())
                    .set(YkfCustomerShopEntity::getStopUserDept, user.getDeptName())
                    .set(YkfCustomerShopEntity::getStopUser, user.getName());
            ykfCustomerShopService.update(updateWrapper);
        } else {
            throw new RRException("参数缺失");
        }
        return R.ok();
    }

    /**
     * 改动记录-分页
     */
    @StringTrim
    @PostMapping("/recordPage")
    public R recordPage(@RequestBody ParamsModel<YkfShopChangeRecordEntity> params) {
        PageUtils page = changeRecordService.queryPage(params);
        return R.ok(page);
    }

    /**
     * 历史记录-分页
     */
    @StringTrim
    @PostMapping("/historyPage")
    public R historyPage(@RequestBody ParamsModel<YkfCustomerShopHistoryEntity> params) {
        if (ObjectUtil.isEmpty(params) || ObjectUtil.isEmpty(params.getCondition()) || ObjectUtil.isEmpty(params.getCondition().getShopId())) {
            throw new RRException("参数缺失，请检查");
        }
        PageUtils page = historyService.queryPage(params);
        return R.ok(page);
    }

    /**
     * 恢复合作
     */
    @PostMapping("/resumeCooperation")
    public R resumeCooperation(@RequestBody YkfCustomerShopEntity shop) {
        if (ObjectUtil.isEmpty(shop) || ObjectUtil.isEmpty(shop.getShopId()) || ObjectUtil.isEmpty(shop.getStartDate()) || ObjectUtil.isEmpty(shop.getEndDate())) {
            throw new RRException("参数Y缺失，请检查");
        }
        YkfCustomerShopEntity shop2 = ykfCustomerShopService.getById(shop.getShopId());
        //查询是否不存在了启用店铺
        QueryWrapper<YkfCustomerShopEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(YkfCustomerShopEntity::getCustomerId, shop.getCustomerId())
                .eq(YkfCustomerShopEntity::getCooperateStatus, 1);
        int count = ykfCustomerShopService.count(queryWrapper);

        UpdateWrapper<YkfCustomerShopEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(YkfCustomerShopEntity::getShopId, shop.getShopId())
                .set(YkfCustomerShopEntity::getStartDate, shop.getStartDate())
                .set(YkfCustomerShopEntity::getEndDate, shop.getEndDate())
                .set(YkfCustomerShopEntity::getCooperateStatus, 1)
                .set(YkfCustomerShopEntity::getRemark, shop.getRemark());
        ykfCustomerShopService.update(updateWrapper);
        if (ObjectUtil.isNotEmpty(shop2)) {
            //更新客户状态
            UpdateWrapper<YkfCustomerEntity> updateWrapper1 = new UpdateWrapper<>();
            updateWrapper1.lambda().eq(YkfCustomerEntity::getCustomerId, shop2.getCustomerId())
                    .set(YkfCustomerEntity::getCooperateStatus, 1)
                    .set(YkfCustomerEntity::getStopCooperateDate, DateUtil.date());
            ykfCustomerService.update(updateWrapper1);
        }

        YkfCustomerShopEntity shop1 = ykfCustomerShopService.getById(shop.getShopId());
        YkfCustomerShopHistoryEntity history = new YkfCustomerShopHistoryEntity();
        BeanUtil.copyProperties(shop1, history);
        history.setOperator(getUser().getName());
        historyService.save(history);
        return R.ok();
    }

    /**
     * 恢复合作
     */
    @PostMapping("/updateGroupShopInfo")
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public R updateGroupShopInfo(@RequestBody YkfCustomerShopEntity shop) {
        if (ObjectUtil.isEmpty(shop) || ObjectUtil.isEmpty(shop.getShopIds())) {
            throw new RRException("参数缺失，请检查");
        }
        UpdateWrapper<YkfCustomerShopEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().in(YkfCustomerShopEntity::getShopId, shop.getShopIds())
                .set(YkfCustomerShopEntity::getMergeGroup, shop.getMergeGroup())
                .set(YkfCustomerShopEntity::getBaseSalary, shop.getBaseSalary());
        ykfCustomerShopService.update(updateWrapper);
        for (Long shopId : shop.getShopIds()) {
            YkfCustomerShopEntity shop1 = ykfCustomerShopService.getById(shopId);
            YkfCustomerShopHistoryEntity history = new YkfCustomerShopHistoryEntity();
            BeanUtil.copyProperties(shop1, history);
            history.setOperator(getUser().getName());
            historyService.save(history);
        }
        return R.ok();
    }

    /**
     * 获取上次店铺联系人信息
     */
    @PostMapping("/getLastShopInfo")
    public R getLastShopInfo(@RequestBody YkfCustomerShopEntity shop) {
        Map<String, Object> resultMap = new HashMap<>();
        if (ObjectUtil.isEmpty(shop) || ObjectUtil.isEmpty(shop.getCustomerId())) {
            throw new RRException("参数缺失，请检查");
        }
        QueryWrapper<YkfCustomerShopEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(YkfCustomerShopEntity::getCustomerId, shop.getCustomerId())
                .orderByDesc(YkfCustomerShopEntity::getCreateTime)
                .last("limit 1");
        YkfCustomerShopEntity one = ykfCustomerShopService.getOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(one)) {
            resultMap.put("contacts", one.getContacts());
            resultMap.put("qq", one.getQq());
            resultMap.put("wechat", one.getWechat());
            resultMap.put("ding", one.getDing());
            resultMap.put("phone", one.getPhone());
        }
        return R.ok(resultMap);
    }
}
